<template>
  <div class="product-management-container">
    <!-- 头部操作区域 -->
    <el-card class="operate-container" shadow="never">
      <el-button type="primary" :icon="Plus" @click="handleCreate">新增产品</el-button>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" shadow="never">
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="产品ID" width="180" />
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="type" label="产品型号" width="180" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination-container"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑产品' : '新增产品'"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form ref="productFormRef" :model="productForm" :rules="rules" label-width="100px">
        <el-form-item label="产品ID" prop="id">
          <el-input v-model="productForm.id" :disabled="isEdit" placeholder="例如：PIM-ROB-001" />
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="产品型号" prop="type">
          <el-input v-model="productForm.type" />
        </el-form-item>
        <el-form-item label="关键参数" prop="reference">
          <el-input v-model="productForm.reference" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getProductPage, saveOrUpdateProduct, deleteProductById } from '@/api/modules/product'

// --- 响应式数据 ---
const loading = ref(true)
const tableData = ref([])
const total = ref(0)
const queryParams = reactive({
  current: 1,
  size: 10
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const productFormRef = ref(null)
const productForm = reactive({
  id: '',
  name: '',
  type: '',
  reference: ''
})
const rules = {
  id: [{ required: true, message: '请输入产品ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }]
}


// 获取产品列表
const fetchProductList = async () => {
  loading.value = true
  try {
    const data = await getProductPage(queryParams)
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取产品列表失败', error)
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.size = size
  fetchProductList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  queryParams.current = current
  fetchProductList()
}

// 重置表单
const resetForm = () => {
  productForm.id = ''
  productForm.name = ''
  productForm.type = ''
  productForm.reference = ''
  // 清除校验状态
  if (productFormRef.value) {
    productFormRef.value.clearValidate()
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}

// 处理新增
const handleCreate = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleUpdate = (row) => {
  isEdit.value = true
  // 使用Object.assign避免直接修改表格行数据
  Object.assign(productForm, row)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该产品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProductById(id)
      ElMessage.success('删除成功')
      // 重新加载列表
      fetchProductList()
    } catch (error) {
      console.error('删除产品失败', error)
    }
  }).catch(() => {
  })
}

// 提交表单
const handleSubmit = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await saveOrUpdateProduct(productForm)
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        // 重新加载列表
        fetchProductList()
      } catch (error) {
        console.error('操作失败', error)
      }
    }
  })
}

onMounted(() => {
  fetchProductList()
})
</script>

<style scoped>
.product-management-container {
  padding: 20px;
}
.operate-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
